<script setup>
import { onMounted,ref } from 'vue';
const box = ref('')
const num = ref(box.value.scrollTop)
onMounted(()=>{
  box.value = document.documentElement
  document.body.onscroll = function(){
    num.value = box.value.scrollTop
  }
})


const ScrollTop = (number = 0, time) => {
  if (!time) {
    box.value.scrollTop = number;
    return number;
  }
  const spacingTime = 20; 
  let spacingInex = time / spacingTime; 
  let nowTop = box.value.scrollTop;
  let everTop = (number - nowTop) / spacingInex;
  let scrollTimer = setInterval(() => {
    if (spacingInex > 0) {
      spacingInex--;
      ScrollTop((nowTop += everTop));
    } else {
      clearInterval(scrollTimer);
    }
  }, spacingTime);
};
</script>

<template>
  <div class="scroll-top" @click="ScrollTop(0, 500)" :style="{opacity: num > 300 ? 1 : 0}">
    ^
  </div>
</template>

<style lang="scss">
  .scroll-top{
    position: fixed;
    width: 50px;
    height: 50px;
    right: 10px;
    bottom: 10px;
    text-align: center;
    line-height: 50px;
    border: 1px solid #f5f5f5;
    opacity: 0;
    transition: all 1s;

    background-color: #fff;
  }
</style>
